﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using OrganizerLibrary.Extensions;
using OrganizerLibrary.Processors;
using OrganizerLibrary.Settings;

namespace OrganizerLibrary
{
    public class Organizer : IDisposable
    {
        private readonly OrganizerContext _context;
        private FileSystemWatcher _watcher;

        private Organizer(OrganizerContext context)
        {
            _context = context;
        }

        public static Organizer Instantiate(OrganizerContext context)
        {
            var organizer = new Organizer(context);
            organizer.Initialize();
            return organizer;
        }

        private void Initialize()
        {
            _watcher = new FileSystemWatcher(_context.WatchDirectory.FullName) { IncludeSubdirectories = false, EnableRaisingEvents = false };
            FileSystemEventHandler action = (sender, e) => FileCreated(e.FullPath);
            _watcher.Created += action;
        }
        
        private void FileCreated(String inboundFilePath)
        {
            FileSystemInfo inboundFileInfo = new FileInfo(inboundFilePath);
            if (inboundFileInfo.Attributes == FileAttributes.Directory)
            {
                return;
            }
            Boolean unmapped = !OrganizerSettings.Instance.ProcessorDictionary.ContainsFileExtension(inboundFileInfo.GetFileExtension());
            if(unmapped && !OrganizerSettings.Instance.RouteNonMapped)
            {
                return;
            }

            Int32 retryAttempts = 0;
            while(inboundFileInfo.IsLocked() && retryAttempts < OrganizerSettings.Instance.NumberOfRetries)
            {
                Thread.Sleep(OrganizerSettings.Instance.PollingPeriodInMilliseconds);
                retryAttempts++;
            }

            if (unmapped)
            {
                OrganizerSettings.Instance.ProcessorDictionary.ProcessUnmapped(inboundFileInfo);
            }
            else
            {
                OrganizerSettings.Instance.ProcessorDictionary.Process(inboundFileInfo);
            }
        }

        public void Start()
        {
            _watcher.EnableRaisingEvents = true;
        }

        public void Stop()
        {
            _watcher.EnableRaisingEvents = false;
        }

        public void Dispose()
        {
            _watcher.Dispose();
        }
    }
}
